window.deepClone = function(obj) {
  return JSON.parse(JSON.stringify(obj));
};

if (typeof String.prototype.startsWith != 'function') {
 String.prototype.startsWith = function (prefix){
  return this.slice(0, prefix.length) === prefix;
 };
}


Array.prototype.insert = function (item) {
  this.splice(0, 0, item);
};

/**
  * ModalHelper helpers resolve the modal scrolling issue on mobile devices
  * https://github.com/twbs/bootstrap/issues/15852
  * requires document.scrollingElement polyfill https://github.com/yangg/scrolling-element
  */
var ModalHelper = (function(bodyCls) {
  var scrollTop;
  return {
    afterOpen: function() {
      scrollTop = document.scrollingElement.scrollTop;
      document.body.classList.add(bodyCls);
      document.body.style.top = -scrollTop + 'px';
    },
    beforeClose: function() {
      document.body.classList.remove(bodyCls);
      // scrollTop lost after set position:fixed, restore it back.
      document.scrollingElement.scrollTop = scrollTop;
    }
  };
})('modal-open');

var wsGet = window.wsGet = function(url, params, okCb, errCb){
    $.ajax({
        url:url,
        type:'GET', //GET
        async:true,    //或false,是否异步
        data:params,
        timeout:10000,    //超时时间
        dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
        success:function(data,textStatus,jqXHR){
            okCb(data);
        },
        error:function(xhr,textStatus){
            errCb();
        }
    })
};

var wsPost = window.wsPost = function(url, params, okCb, errCb){
    $.ajax({
        url:url,
        type:'POST', //GET
        async:true,    //或false,是否异步
        data:params,
        timeout:10000,    //超时时间
        dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        success:function(data,textStatus,jqXHR){
            okCb(data);
        },
        error:function(xhr,textStatus){
            errCb();
        }
    })
}

Vue.filter('formatAsRmb', function(val){
    return (val / 100).toFixed(2);
});

Vue.filter('formatAsHref', function(val){
    if(val.startsWith('http://') || val.startsWith('https://')){
        return val;
    }
    return 'javascript:;';
});

Vue.filter('formatAsDatetime', function(val){
    var date = new Date(val);
    var fmt = "yyyy-MM-dd HH:mm:ss";
    var o = {
        "M+" : date.getMonth()+1, //月份
        "d+" : date.getDate(), //日
        "h+" : date.getHours()%12 == 0 ? 12 : date.getHours()%12, //小时
        "H+" : date.getHours(), //小时
        "m+" : date.getMinutes(), //分
        "s+" : date.getSeconds(), //秒
        "q+" : Math.floor((date.getMonth()+3)/3), //季度
        "S" : date.getMilliseconds() //毫秒
    };
    var week = {
        "0" : "/u65e5",
        "1" : "/u4e00",
        "2" : "/u4e8c",
        "3" : "/u4e09",
        "4" : "/u56db",
        "5" : "/u4e94",
        "6" : "/u516d"
    };
    if(/(y+)/.test(fmt)){
        fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
    if(/(E+)/.test(fmt)){
        fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[date.getDay()+""]);
    }
    for(var k in o){
        if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
    return fmt;
});

Vue.filter('formatAsSimpleDatetime', function(val){
    var date = new Date(val);
    var fmt = "MM-dd HH:mm:ss";
    var o = {
        "M+" : date.getMonth()+1, //月份
        "d+" : date.getDate(), //日
        "h+" : date.getHours()%12 == 0 ? 12 : date.getHours()%12, //小时
        "H+" : date.getHours(), //小时
        "m+" : date.getMinutes(), //分
        "s+" : date.getSeconds(), //秒
        "q+" : Math.floor((date.getMonth()+3)/3), //季度
        "S" : date.getMilliseconds() //毫秒
    };
    var week = {
        "0" : "/u65e5",
        "1" : "/u4e00",
        "2" : "/u4e8c",
        "3" : "/u4e09",
        "4" : "/u56db",
        "5" : "/u4e94",
        "6" : "/u516d"
    };
    if(/(y+)/.test(fmt)){
        fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
    if(/(E+)/.test(fmt)){
        fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[date.getDay()+""]);
    }
    for(var k in o){
        if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
    return fmt;
});

/**
 * 将日期格式化成指定格式的字符串
 * @param date 要格式化的日期，不传时默认当前时间，也可以是一个时间戳
 * @param fmt 目标字符串格式，支持的字符有：y,M,d,q,w,H,h,m,S，默认：yyyy-MM-dd HH:mm:ss
 * @returns 返回格式化后的日期字符串
 */
window.formatDate = function (date, fmt){
    date = date == undefined ? new Date() : date;
    date = typeof date == 'number' ? new Date(date) : date;
    fmt = fmt || 'yyyy-MM-dd HH:mm:ss';
    var obj =
    {
        'y': date.getFullYear(), // 年份，注意必须用getFullYear
        'M': date.getMonth() + 1, // 月份，注意是从0-11
        'd': date.getDate(), // 日期
        'q': Math.floor((date.getMonth() + 3) / 3), // 季度
        'w': date.getDay(), // 星期，注意是0-6
        'H': date.getHours(), // 24小时制
        'h': date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, // 12小时制
        'm': date.getMinutes(), // 分钟
        's': date.getSeconds(), // 秒
        'S': date.getMilliseconds() // 毫秒
    };
    var week = ['天', '一', '二', '三', '四', '五', '六'];
    for(var i in obj)
    {
        fmt = fmt.replace(new RegExp(i+'+', 'g'), function(m)
        {
            var val = obj[i] + '';
            if(i == 'w') return (m.length > 2 ? '星期' : '周') + week[val];
            for(var j = 0, len = val.length; j < m.length - len; j++) val = '0' + val;
            return m.length == 1 ? val : val.substring(val.length - m.length);
        });
    }
    return fmt;
}

/**
 * 获取周一或者周日
 * @param type 's'为周一， 'e'为周日
 * @param dates 正整数表示获取下周的，负整数表示获取上周的，零表示本周，数字表示周数
 * @returns 返回格式化后的日期字符串
 */
window.getMonday = function(type, dates) {
    var now = new Date();
    var nowTime = now.getTime();
    var day = now.getDay();
    var longTime = 24 * 60 * 60 * 1000;
    var n = longTime * 7 * (dates || 0);
    if (type == "s") {
        var dd = nowTime - (day - 1) * longTime + n;
    };
    if (type == "e") {
        var dd = nowTime + (7 - day) * longTime + n;
    };
    dd = new Date(dd);
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1;
    var d = dd.getDate();
    m = m < 10 ? "0" + m: m;
    d = d < 10 ? "0" + d: d;
    var day = y + "-" + m + "-" + d;
    return day;
};

/**
 * 将字符串解析成日期
 * @param str 输入的日期字符串，如'2014-09-13'
 * @param fmt 字符串格式，默认'yyyy-MM-dd'，支持如下：y、M、d、H、m、s、S，不支持w和q
 * @returns 解析后的Date类型日期
 */
window.parseDate = function (str, fmt){
    fmt = fmt || 'yyyy-MM-dd';
    var obj = {y: 0, M: 1, d: 0, H: 0, h: 0, m: 0, s: 0, S: 0};
    fmt.replace(/([^yMdHmsS]*?)(([yMdHmsS])\3*)([^yMdHmsS]*?)/g, function(m, $1, $2, $3, $4, idx, old)
    {
        str = str.replace(new RegExp($1+'(\\d{'+$2.length+'})'+$4), function(_m, _$1)
        {
            obj[$3] = parseInt(_$1);
            return '';
        });
        return '';
    });
    obj.M--; // 月份是从0开始的，所以要减去1
    var date = new Date(obj.y, obj.M, obj.d, obj.H, obj.m, obj.s);
    if(obj.S !== 0) date.setMilliseconds(obj.S); // 如果设置了毫秒
    return date;
}


/**
 * 自定义对话框
 */
$(function(){

    var tmpl = $('#dialog-tmpl').html();

    $('body').append(tmpl);

    window.dialog = new Vue({
        el: '#dialog',
        data: {
            show: false, //是否显示
            mode: '', //confirm, alert, agreement
            confirmData: {
                icon: 'warn',
                title: '标题',
                content: '确认保存？',
                actions: {
                    defaultBtn: '不是',
                    primaryBtn: '是的'
                }
            },
            alertData: {
                icon: 'warn',
                title: '',
                content: '',
                actions: {
                    primaryBtn: '我知道了'
                }
            },
            agreementData: {
                title: '使用协议',
                content: '',
                actions: {
                    primaryBtn: '我同意以上协议'
                }
            }
        },
        methods: {
            confirm: function(opts){
                this.show = true;
                this.mode = 'confirm';
                this.confirmData.icon = opts.icon || 'warn';
                this.confirmData.title = opts.title;
                this.confirmData.content = opts.content;
                this.confirmData.actions.defaultBtn = opts.btns[0];
                this.confirmData.actions.primaryBtn = opts.btns[1];
                this.opts = opts;
            },
            doConfirmAction: function(btn){
                this.show = false;
                this.mode = '';
                if(this.opts && this.opts.callback){
                    this.opts.callback(btn);
                }
                this.opts = null;
            },
            alert: function(opts){
                this.show = true;
                this.mode = 'alert';
                this.alertData.icon = opts.icon || 'warn';
                this.alertData.title = opts.title;
                this.alertData.content = opts.content;
                this.alertData.actions.primaryBtn = opts.btn;
                this.opts = opts;
            },
            doAlertAction: function(btn){
                this.show = false;
                this.mode = '';
                if(this.opts && this.opts.callback){
                    this.opts.callback(btn);
                }
                this.opts = null;
            },
            agreement: function(opts){
                this.show = true;
                this.mode = 'agreement';
                this.agreementData.title = opts.title || this.agreementData.title;
                this.agreementData.content = opts.content || this.agreementData.content;
                this.agreementData.actions.primaryBtn = opts.btn || this.agreementData.actions.primaryBtn;
                this.opts = opts;
                ModalHelper.afterOpen();
            },
            doAgreementAction: function(btn){
                this.show = false;
                this.mode = '';
                if(this.opts && this.opts.callback){
                    this.opts.callback(btn);
                }
                this.opts = null;
                ModalHelper.beforeClose();
            },
            closeAgreementDialog: function(){
                this.show = false;
                this.mode = '';
                this.opts = null;
                ModalHelper.beforeClose();
            }

        }
    });


});

/**
 * 加载大菊花
 */
$(function(){

    var tmpl = $('#loading-tmpl').html();

    $('body').append(tmpl);

    window.loadingToast = new Vue({
        el: '#loadingToast',
        data: {
            show: false //是否显示

        },
        methods: {
            display: function(){
                this.show = true;
            },
            hide: function(){
                this.show = false;
            },
        }
    });


});

/**
 * toast
 */
$(function(){

    var tmpl = '<p class="toast-text" id="toastText" ></p>';

    $('body').append(tmpl);

    var toastTimeout;

    window.toast = function(text){
        clearTimeout(toastTimeout);
        var $t = $('#toastText');
        $t.html(text);
        $t.show();
        toastTimeout = setTimeout(function(){
            $t.addClass('hide');
            setTimeout(function(){
                $t.hide();
                $t.removeClass('hide');
            }, 300);

        },2000);
    }

});

/**
 * 设置页面标题
 */
window.setWindowTitle = function (title) {
  document.title = title;
  var $body = $('body');
  var $iframe = $('<iframe style="display: none" src="http://oss.image.djcars.cn/one-pixel.png"></iframe>');
//  $iframe.on('load',function() {
//    setTimeout(function() {
//        $iframe.off('load').remove();
//    }, 100);
//  }).appendTo($body);

    $iframe.appendTo($body);
}

$(function(){
    var timer;
    var gap = 50;
    //是否已经滚到底部
    window.isScrollBottom = false;
    window.isScrollTop = false;

    function scrollFn(){
        //真实内容的高度
        var pageHeight = Math.max(document.body.scrollHeight,document.body.offsetHeight);
        //视窗的高度
        var viewportHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0;
        //隐藏的高度
        var scrollHeight = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

        window.isScrollBottom = pageHeight - viewportHeight - scrollHeight < gap;

        if(window.isScrollBottom){//如果满足触发条件，执行
            if(!!window.onScrollToBottom){
                window.onScrollToBottom();
            }
        }

        window.isScrollTop = scrollHeight < gap;

        if(window.isScrollTop){//如果满足触发条件，执行
            if(!!window.onScrollToTop){
                window.onScrollToTop();
            }
        }
    }

    $(window).bind("scroll",function(){
        clearTimeout(timer);
        timer = setTimeout(scrollFn, 300);
    });//绑定滚动事件

    /**
     * 滚动到底部
     */
    window.scrollToBottom = function(){
        //真实内容的高度
        var pageHeight = Math.max(document.body.scrollHeight,document.body.offsetHeight);
        $('html,body').animate({scrollTop:pageHeight}, 300);
    }

    /**
     * 滚动到顶部
     */
    window.scrollToTop = function(){
        $(window).scrollTop(0);
    }

});



//微信分享
(function(){
    if(!window.wx){
        console.log('没有加载微信js，不执行微信相关初始化');
        return;
    }
    function init() {

    	wx.config({
    		debug : false,
    		appId : appId,
    		timestamp : timeStamp,
    		nonceStr : nonceStr,
    		signature : signature,
    		jsApiList : ['onMenuShareTimeline','onMenuShareAppMessage']
    	});
    };

    init();

    wx.ready(function(){
        if($('[wx-no-share]').length > 0){
            wx.hideOptionMenu(); //隐藏分享
        }

    });
})();